//
// Created by HhL on 2021/7/8.
//
#include <stdio.h>
#include "../../include/c_utils.h"

void write_struct(const char* file_name);

void read_struct();

void read_struct2();

char pathname[] = "/Users/hhl/Desktop/Architecture/jvm/c_study/file/struct_stu.txt";
typedef struct student {
    int age;
    char name[10];
    int num;
} stu_t;

int main() {
//    printf("最终的目标字符串长度大小 s1 -s2：%d\n", 1);
//    write_struct(pathname);
//    read_struct();
    read_struct2();
    return 0;
}


// 一次读一个元素。
void read_struct() {
    FILE* fp = fopen(pathname, "r");
    if (!fp) {
        perror("fopen error");
    }
    stu_t s1;

    int ret = fread(&s1, 1, sizeof(stu_t), fp);
    printf("ret = %d\n", ret);

    printf("age = %d, name=%s, num = %d\n", s1.age, s1.name, s1.num);

    fclose(fp);
}

void write_struct(const char* file_name) {
    stu_t stu[4] = {
            18, "afei", 10,
            20, "andy", 20,
            30, "lily", 30,
            16, "james", 40
    };

    FILE* fp = fopen(file_name, "w");
    if (!fp) {
        perror("fopen error");
    }

    int ret = fwrite(&stu[0], 1, sizeof(stu_t) * 4, fp);//2进制
    if (ret == 0) {
        perror("fwrite error");
    }

    printf("ret = %d\n", ret);

    fclose(fp);
}